package com.sgb.member.ui.activity

import android.content.Context
import android.content.Intent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.tabs.TabLayout
import com.sgb.member.MemberConfig
import com.sgb.member.R
import com.sgb.member.databinding.ActivityRemoveMemberBinding
import com.sgb.member.entity.RemoveMemberBean
import com.sgb.member.ui.adapter.RemberMemberAdapter
import com.sgb.member.view_model.RemoveMemberModel
import com.swgk.core.base.AppActivity
import com.swgk.core.customview.XCustomTabLayout
import com.swgk.core.dialog.DialogHelper
import com.swgk.core.util.MToast
import com.swgk.core.view.selection.CommonPopEntity
import com.swgk.core.xrecyclerview.LoadingMoreFooter
import com.swgk.core.xrecyclerview.XRecyclerView

/**
 * 已解除会员列表
 */
class RemoveMemberActivity : AppActivity() {
    private lateinit var viewModel: RemoveMemberModel
    private lateinit var mBinding: ActivityRemoveMemberBinding
    lateinit var mAdapter: RemberMemberAdapter
    var type = "2"//供需关系1:供方2:需方
    var tab_1 = "";
    var tab_2 = "";

    var keyWord = ""
    var datas = mutableListOf<RemoveMemberBean>()

    companion object {
        fun jumptAct( Context: Context) {
            Context.startActivity(Intent(Context, RemoveMemberActivity::class.java))
        }
    }

    var topTabDatas = ArrayList<CommonPopEntity>().apply {
        add(CommonPopEntity("2", "需方会员"))
        add(CommonPopEntity("1", "供方会员"))
    }
    var tabDatas = ArrayList<CommonPopEntity>()
    var secondTabDatas = mutableListOf<CommonPopEntity>()
    override fun initView() {
        super.initView()
        viewModel = ViewModelProvider(this).get(RemoveMemberModel::class.java)
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_remove_member)
        mBinding.lifecycleOwner = this
        mBinding.ivBack.setOnClickListener { finish() }
        initTab()
        initRecycler()
        initEdit()
        receiverLiveData()
        viewModel.getTabData(type)
        loadData()
    }

    fun initEdit() {
        mBinding.etSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                keyWord = mBinding.etSearch.text.toString().trim()
                loadData()
            }
            hideSoftInputFromWindow()
            false
        }
        mBinding.tvSearch.setOnClickListener {
            keyWord = mBinding.etSearch.text.toString().trim()
            loadData()
        }
    }


    private fun receiverLiveData() {
        viewModel.tabDatasLiveData.observe(this, Observer {
            showChildTab(it)
        })
        viewModel.datasLiveData.observe(this, {
            setRecyclerViewData(it)
        })
        viewModel.isLoadLiveData.observe(this, {
            showOrHideDialog(it)
        })
        viewModel.msgLiveData.observe(this, {
            MToast.showLongToast(this, it)
        })
        viewModel.urlH5LiveData.observe(this,{
            MemberConfig.getInstance().startWebViewX5(this, it)
        })
    }

    private fun setRecyclerViewData(it: List<RemoveMemberBean?>?) {
        closeRecyclerRefreshing()
        if (it?.size ?: 0 < 10) {
            mBinding.recyclerView.setNoMore(true)
        } else {
            mBinding.recyclerView.setNoMore(false)
        }
        if (isLoadMore) {
            datas.addAll(it as ArrayList<RemoveMemberBean>)
        } else {
            datas.clear()
            datas.addAll(it as ArrayList<RemoveMemberBean>)
        }
        if (datas.size > 0) {
            mBinding.emptyView.visibility = View.GONE
            mBinding.recyclerView.visibility = View.VISIBLE
        } else {
            mBinding.emptyView.visibility = View.VISIBLE
            mBinding.recyclerView.visibility = View.GONE
        }
        mAdapter.notifyDataSetChanged()
    }

    fun closeRecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete()
        mBinding.recyclerView.loadMoreComplete()
    }

    //顶部tab
    fun initTab() {
        for (i in topTabDatas.indices) {
            mBinding.tabTop.addTab(mBinding.tabTop.newTab().setText(topTabDatas[i].typeName))
        }
        mBinding.tabTop.tabMode = TabLayout.MODE_FIXED
        mBinding.tabTop.setNormalColor(R.color.color_F5F5F5)
        mBinding.tabTop.setSelectColor(R.color.color_FFFFFF)
        mBinding.tabTop.setNormalSize(15)
        mBinding.tabTop.setSelectSize(18)
        mBinding.tabTop.addOnTabSelectedListener(topTabDatas,
            object : XCustomTabLayout.SimpleSelectedListener() {
                override fun onTabSelected(tab: TabLayout.Tab) {
                    val pos = tab.position
                    type = topTabDatas[pos].no
                    viewModel.getTabData(type)
                    tab_1 = ""
                    tab_2 = ""
                    tabDatas.clear()
                    secondTabDatas.clear()
                    mBinding.childTabLayout.visibility = View.GONE
                    loadData()
                }
            })
    }

    //设置二级tab
    private fun showChildTab(data: List<CommonPopEntity?>?) {
        data?.let {
            tabDatas.clear()
            tabDatas.add(CommonPopEntity("", "全部"))
            tabDatas.addAll(it as ArrayList<CommonPopEntity>)
            mBinding.tabLayout.apply {
                visibility = View.VISIBLE
                removeAllTabs()
                for (i in tabDatas.indices) {
                    addTab(newTab().setText(tabDatas[i].typeName))
                }
                setNormalColor(R.color.color_title_medium)
                addOnTabSelectedListener(tabDatas, object : XCustomTabLayout.SimpleSelectedListener() {
                    override fun onTabSelected(tab: TabLayout.Tab) {
                        tab_1 = tabDatas[tab.position].no
                        tab_2 = ""
                        loadData(false)
                        secondTabDatas.clear()
                        mBinding.childTabLayout.visibility = View.GONE
                        showThreeChildTab(tabDatas[tab.position].children)
                    }
                })
            }
        }

    }

    //设置三级tab
    private fun showThreeChildTab(data: List<CommonPopEntity?>?) {
        data?.let {
            if (it.isEmpty()) {
                return
            }
            secondTabDatas.clear()
            secondTabDatas.add(CommonPopEntity("", "全部"))
            secondTabDatas.addAll(it as ArrayList<CommonPopEntity>)
            mBinding.childTabLayout.apply {
                visibility = View.VISIBLE
                removeAllTabs()
                for (d in secondTabDatas) {
                    addTab(newTab().setText(d.typeName))
                }
                setNormalColor(R.color.color_title_small)
                getTabAt(0)?.select()
                addOnTabSelectedListener(secondTabDatas,
                    object : XCustomTabLayout.SimpleSelectedListener() {
                        override fun onTabSelected(tab: TabLayout.Tab) {
                            tab_2 = secondTabDatas[tab.position].no
                            loadData(false)
                        }
                    })
            }
        }
    }

    private fun initRecycler() {
        mBinding.recyclerView.setPullRefreshEnabled(true)
        mBinding.recyclerView.setLoadingMoreEnabled(true)
        val footer = mBinding.recyclerView.footView as LoadingMoreFooter
        footer.setNoMoreHint("已经到底啦~")
        mBinding.recyclerView.setLoadingListener(object : XRecyclerView.LoadingListener {
            override fun onRefresh() {
                loadData()
            }

            override fun onLoadMore() {
                loadData(true)
            }
        })
        mAdapter = RemberMemberAdapter(this,datas, ::callBack)
        mBinding.recyclerView.adapter = mAdapter

    }
    //跳H5详情
    fun callBack(bean: RemoveMemberBean) {
        viewModel.getUrlSetting("removedDetail", "?no=${bean.no}")
    }

    var isLoadMore: Boolean = false
    fun loadData(isLoadMore: Boolean = false) {
        this.isLoadMore = isLoadMore
        viewModel.loadDatas(isLoadMore, type, tab_1, tab_2, keyWord)
    }

    /**隐藏软禁盘**/
    fun hideSoftInputFromWindow() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    fun showOrHideDialog(aBoolean: Boolean) {
        if (aBoolean) {
            if (!DialogHelper.isShowing()) {
                DialogHelper.showProgressDialog(this, "数据获取中...")
            }
        } else {
            DialogHelper.dismissProgressDialog()
        }
    }
}


